{
 "metadata": {
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4-final"
  },
  "orig_nbformat": 2,
  "kernelspec": {
   "name": "python3",
   "display_name": "Python 3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2,
 "cells": [
  {
   "source": [
    "# 7 基本扩展模块"
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "source": [
    "## 上机练习 1： 计时和文件处理"
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "source": [
    "### 1.给算法计时"
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "source": [
    "看看阶乘累加 (n = 1 ～ 100) 各需要多长时间？"
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "94269001683709979260859834124473539872070722613982672442938359305624678223479506023400294093599136466986609124347432647622826870038220556442336528920420940313\n一共花费 0.001323 秒\n"
     ]
    }
   ],
   "source": [
    "import time\n",
    "\n",
    "def factorial(n):\n",
    "    product = 1\n",
    "    for i in range(1, n+1):\n",
    "        product *= i\n",
    "    return product\n",
    "\n",
    "\n",
    "n = 100\n",
    "total = 0\n",
    "start = time.time()\n",
    "for i in range(1, n + 1):\n",
    "    total += factorial(i)\n",
    "end = time.time()\n",
    "print(total)\n",
    "print(\"一共花费 %f 秒\" % (end - start))"
   ]
  },
  {
   "source": [
    "### 2.文本文件写入"
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "source": [
    "将一篇文章写入一个文本文件"
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [],
   "source": [
    "paper = \"My name is Lihua. I am from Mars. I have many hobbies, such as basketball, reading and painting. However, my favourite one is programming using Python. Thus, my dream is being a program farmer. ^_^\"\n",
    "\n",
    "paper = paper.split(' ')\n",
    "paper = '\\n'.join(paper)  # 必须加入 '\\n' 才能用 writelines 逐行写入\n",
    "\n",
    "with open('paper.txt', 'w') as f:  # 如没有该文件，将 'w' 改为 'x'\n",
    "    f.writelines(paper)"
   ]
  },
  {
   "source": [
    "### 3.文本文件读取"
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "source": [
    "读出文本文件，统计单词数输出\n",
    "\n",
    "读出文本文件，随机输出其中的 10 个单词"
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "共有 35 个单词\n['dream\\n', 'many\\n', 'painting.\\n', 'a\\n', 'from\\n', 'However,\\n', 'is\\n', 'reading\\n', 'my\\n', 'such\\n']\n"
     ]
    }
   ],
   "source": [
    "import random\n",
    "\n",
    "with open('paper.txt', 'r') as f:\n",
    "    strlist = f.readlines()\n",
    "    words_num = len(strlist)\n",
    "    print(\"共有 %d 个单词\" % words_num)\n",
    "    \n",
    "    rand_output = random.sample(strlist, 10)  # 随即输出 10 个单词\n",
    "    print(rand_output)"
   ]
  },
  {
   "source": [
    "## 上机练习 2: 简单绘图"
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "source": [
    "### 1.简单绘图"
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "source": [
    "利用 `turtle` 模块，进行图形绘制"
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "source": [
    "* 绘制一个边长为 100 的绿色正方形 （请在 cmd 或 shell 下运行）"
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import turtle\n",
    "\n",
    "t = turtle.Turtle()\n",
    "t.pencolor('green')\n",
    "w = turtle.Screen()\n",
    "\n",
    "for i in range(4):\n",
    "    t.forward(100)\n",
    "    t.left(90)\n",
    "\n",
    "turtle.done()"
   ]
  },
  {
   "source": [
    "* 绘制一个边长为 100 的红色五角星（请在 cmd 或 shell 下运行）"
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import turtle\n",
    "\n",
    "t = turtle.Turtle()\n",
    "t.pencolor('red')\n",
    "w = turtle.Screen()\n",
    "\n",
    "for i in range(5):\n",
    "    t.forward(100)\n",
    "    t.left(144)\n",
    "\n",
    "turtle.done()"
   ]
  },
  {
   "source": [
    "### 2.绘制一棵树"
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "source": [
    "调用 `turtle` 模块画一棵树，包括枝干和树叶，并涂上颜色（请在 cmd 或 shell 下运行）"
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import turtle\n",
    "\n",
    "def tree(branchlen, t):\n",
    "    if branchlen > 5:\n",
    "        t.forward(branchlen)     # 树干\n",
    "        t.right(20)\n",
    "        tree(branchlen - 15, t)\n",
    "        t.left(40)\n",
    "        tree(branchlen - 15, t)\n",
    "        t.right(20)\n",
    "        t.backward(branchlen)    # 返回原点 \n",
    "\n",
    "\n",
    "t = turtle.Turtle()\n",
    "mywin = turtle.Screen()\n",
    "t.left(90)  # 由于画笔初始是朝右的，树要往上画\n",
    "t.up()\n",
    "t.backward(100)  # 往下退 100，不从中心画起\n",
    "t.down()\n",
    "t.color(\"green\")\n",
    "tree(75, t)\n",
    "mywin.exitonclick()"
   ]
  }
 ]
}